import router from '@/router' // 路由
import NProgress from 'nprogress' // 加载线条
import 'nprogress/nprogress.css'
import store from '@/vuex/store'
import { getToken } from '@/utils/TokenUtil'
const allowList = ['Login'] // no redirect allowList
const loginRoutePath = '/login'
import getPageTitle from '@/utils/getPageTitle'
// 路由跳转前
router.beforeEach((to, from, next) => {
    NProgress.start()
    document.title = getPageTitle(to.meta.title)
    if (allowList.includes(to.name)) {
        next()
        NProgress.done()
        return
    }
    let token = getToken()
    console.log(token)
    if (token) {
        const userInfo = store.getters.userInfo
        console.log("用户信息：", userInfo);
        if (!userInfo || !userInfo.id) {
            // 获取用户信息
            store.dispatch('GET_USER_INFO').then(userInfo => {
                // 根据用户角色资源动态设置路由
                store.dispatch('GenerateRoutes', userInfo).then((res) => {
                    router.addRoutes(res)
                    // 请求带有 redirect 重定向时，登录自动重定向到该地址
                    const redirect = decodeURIComponent(from.query.redirect || to.path)
                    if (to.path === redirect) {
                        // set the replace: true so the navigation will not leave a history record
                        next({ ...to, replace: true }) // 操作重新导航一次，为了触发next放行
                    } else {
                        // 跳转到重定向目的路由
                        next({ path: redirect })
                    }
                })
            }).catch(() => {
                NProgress.done()
            })
        } else {
            next()
        }
    } else {
        // next({ path: loginRoutePath, query: { redirect: to.path } })
        next({ path: loginRoutePath })
        NProgress.done()
    }
})

// 路由跳转后
router.afterEach(() => {
    NProgress.done()
})